<template>
  <div class="ios">
    <div class="w-full h-[77px] flex justify-center items-center flex-col">
      <div class="text-[14px] font-bold">{{ Info.name }}</div>
      <div class="mt-[5px] text-[10px]">由{{ Info.brand }}承保</div>
    </div>
    <div>
      <insureTitle title="保险日期"></insureTitle>
      <div class="p-[15px]">
        <div class="flex items-center justify-between" @click="openPicker(0)">
          <div class="flex text-[14px]">
            <div>生效日期</div>
            <div class="ml-[50px]">
              {{ startTimer }}
              00:00:00
            </div>
          </div>
          <div>
            <img :src="getAssetsFile('home/date.png')" class="w-[14px] h-[14px]" />
          </div>
        </div>
        <div class="border-b border-[#ECECEC] my-[15px]"></div>
        <div class="flex items-center justify-between text-[#c8c9cc]">
          <div class="flex text-[14px]">
            <div>结束日期</div>
            <div class="ml-[50px]">
              <!-- {{ endTimer ? endTimer : year + "-" + month + "-" + strDate }} -->

              <!-- 23:59:59 -->
              {{ endTimer ? endTimer + " 23:59:59" : "" }}
            </div>
          </div>
          <div>
            <img :src="getAssetsFile('home/date.png')" class="w-[14px] h-[14px]" />
          </div>
        </div>
        <div class="border-b border-[#ECECEC] my-[15px]"></div>
        <div class="flex items-center justify-between" @click="openPicker(2)">
          <div class="flex text-[14px]">
            <div>有效天数</div>
            <div class="ml-[50px]" :class="{ 'text-[#c8c9cc]': !edit }">
              {{ days ? days + "天" : "请选择" }}
            </div>
          </div>
          <div>
            <img :src="getAssetsFile('home/date.png')" class="w-[14px] h-[14px]" />
          </div>
        </div>
      </div>
    </div>
    <div>
      <van-form ref="formRef" label-width="98">
        <van-cell-group inset>
          <div>
            <insureTitle title="投保人信息"></insureTitle>
            <tbrxx
              ref="tbrxxRef"
              :infoTbrxx="infoTbrxx"
              :Info="Info"
              :edit="edit"
              :addInfo="Info"
            ></tbrxx>
          </div>
          <div>
            <insureTitle title="职业类别"></insureTitle>
            <category
              ref="categoryRef"
              :category="categoryArr"
              :Info="infoCategory"
              :edit="edit"
            ></category>
          </div>
          <!-- <div>
            <insureTitle title="施工地址"></insureTitle>
            <addressVue
              ref="addressVueRef"
              :edit="edit"
              :addInfo="Info"
            ></addressVue>
          </div> -->
          <div>
            <insureTitle title="保险责任"></insureTitle>
            <responsibility
              :duty="Info.duty"
              :start_time="startTimer"
              :end_time="endTimer"
              ref="responsibilityRef"
              :edit="edit"
              :param="param"
              :fananCost="param.fananCost"
              :personCost="personCost"
              @onConfirm="onConfirm"
              @change="change"
            ></responsibility>
          </div>
          <div>
            <insureTitle title="被保人清单"></insureTitle>
            <user :user="param.user" :edit="edit" ref="userRef"></user>
          </div>
          <!-- <div v-if="route.query.order_id && Info.state == '2'">
            <insureTitle title="保单信息"></insureTitle>
            <bdProfile :bdInfo="Info" @getInfo="getInfo"></bdProfile>
          </div> -->
        </van-cell-group>
        <div
          class="flex px-[15px] pb-[15px]"
          v-if="(routeType == '1' || routeType == '3') && edit"
        >
          <div @click="checked = !checked" class="mt-[2px]">
            <img
              v-if="checked"
              :src="getAssetsFile('insure/active.png')"
              class="min-w-[14px] h-[14px]"
            />
            <img
              v-else
              :src="getAssetsFile('insure/noactive.png')"
              class="min-w-[14px] h-[14px]"
            />
          </div>
          <div class="ml-[10px] text-[14px]">
            购买前，请仔细阅读<span class="text-[#EF6800]" @click="clickPush(1)"
              >《投保须知》</span
            ><span class="text-[#EF6800]" @click="clickPush(2)">《特别约定》</span
            ><span class="text-[#EF6800]" @click="clickPush(3)">《产品条款》</span
            ><span class="text-[#EF6800]" @click="clickPush(4)">《保单样本》</span>
          </div>
        </div>

        <!-- 填写投保信息 -->
        <div class="w-full h-[60px] flex items-center ios" v-if="routeType == '3'">
          <div
            class="flex-1 text-[#f3a140] font-bold flex justify-center items-center h-[60px] text-[20px]"
          >
            ￥{{ cost.toFixed(2) }}
          </div>
          <div class="flex items-center justify-center px-[15px] flex-1" @click="share">
            <img :src="getAssetsFile('home/share.png')" class="w-[16px] h-[16px]" />
            <div class="text-[14px] text-[#636363] ml-[5px]">分享</div>
          </div>
          <div
            @click="openNotice()"
            class="h-[60px] flex-1 flex justify-center items-center text-white"
            style="background: linear-gradient(180deg, #f3a140 0%, #f38e40 100%)"
          >
            立即投保
          </div>
        </div>
        <!-- 修改投保信息 -->
        <div
          class="w-full h-[60px] flex items-center ios"
          v-if="route.query.order_id && routeType == '1'"
        >
          <div
            class="flex-1 text-[#f3a140] font-bold flex justify-center items-center h-[60px] text-[20px]"
          >
            ￥{{ cost.toFixed(2) }}
          </div>
          <div class="flex items-center justify-center mx-[15px] flex-1" @click="Edit">
            <div class="text-[#636363] ml-[5px]">修改</div>
          </div>
          <div
            @click="pay"
            class="h-[60px] flex-1 flex justify-center items-center text-white"
            style="background: linear-gradient(180deg, #f3a140 0%, #f38e40 100%)"
          >
            <span>{{ edit ? "提交保单" : "确认支付" }}</span>
          </div>
        </div>
      </van-form>
    </div>
    <van-popup v-model:show="showBottom" position="bottom" safe-area-inset-bottom>
      <van-date-picker
        v-if="type == 0"
        :filter="filter"
        title="选择日期"
        v-model="currentDate"
        @cancel="showBottom = false"
        @confirm="pickerConfirm"
        @change="pickerChnage"
      />
      <van-picker
        v-if="type == 2"
        title="有效天数"
        :columns="dataSelect[0]"
        :columns-field-names="{ text: 'text', value: 'text' }"
        @confirm="pickerConfirm"
        @cancel="showBottom = false"
      />
    </van-popup>
    <!-- 条款 -->
    <div>
      <van-popup
        round
        v-model:show="articleShow"
        position="center"
        safe-area-inset-bottom
      >
        <div
          v-for="item in Info.doc"
          class="rounded-[10px] p-[10px]"
          @click="clickArticle(item, 3)"
        >
          <div class="text-[14px] text-blue-300">{{ item.title }}</div>
        </div>
      </van-popup>
    </div>
  </div>
  <!-- 遮阳罩 -->
  <div>
    <van-overlay :show="overlayShow" />
  </div>
  <!-- 投保须知弹窗 -->
  <div>
    <van-popup
      round
      v-model:show="noticeShow"
      position="center"
      safe-area-inset-bottom
      :close-on-click-overlay="false"
    >
      <div class="rounded-[10px] px-[10px] pt-[10px] pb-[60px] h-[400px] relative">
        <div class="flex justify-center items-centern font-bold text-[20px]">
          投保须知
        </div>
        <div class="" v-html="Info.notice"></div>
        <div class="bg-white flex justify-center items-center sticky bottom-0 py-[10px]">
          <van-button type="primary" :disabled="dialogTime > 0" @click="sumbit"
            >我已全部阅读<span v-if="dialogTime">（{{ dialogTime }}s）</span>
          </van-button>
        </div>
      </div>
    </van-popup>
  </div>
</template>
<script setup lang="ts">
import insureTitle from "./insureTitle.vue"; //标题
import tbrxx from "./tbrxx.vue"; //投保人信息
import category from "./category.vue"; //职业类别
import responsibility from "./responsibility.vue"; //保险责任
import upload from "./upload.vue";
// import bdProfile from "./bdProfile.vue"; //保单信息
import user from "./user.vue"; //被保人清单
import fjInsured from "./fjInsured.vue"; //附加被保人
import addressVue from "./address.vue";
import getAssetsFile from "@/utils/getImageurl";
import { showToast, type FormInstance } from "vant";
import { ref, computed, reactive, watchEffect } from "vue";
import { useRouter, useRoute, onBeforeRouteLeave } from "vue-router";
import ys from "./ys.vue"; //标的要素
import {
  getInsureInfo,
  addOrder,
  orderDetail,
  getJobClassify,
  submitApi,
} from "@/utils/api";
import * as rrweb from "rrweb";
import { listenerHandler } from "_@rrweb_types@2.0.0-alpha.16@@rrweb/types";
const router = useRouter();
const route = useRoute();
const showBottom = ref(false);
const type = ref(0); //0是选择生效时间 2是选择有效天数
const routeType = ref(""); //1是去支付，2是查看详情 3是投保
const startTimer = ref("");
const endTimer = ref("");
const year = ref<any>();
const month = ref<any>();
const noticeShow = ref(false); //投保须知弹窗
const articleShow = ref(false);
const dataSelect = ref([
  [
    {
      text: "31",
      value: "16",
    },
    {
      text: "92",
      value: "29",
    },
    {
      text: "183",
      value: "46",
    },
    {
      text: "365",
      value: "65",
    },
  ],
  [
    {
      text: "31",
      value: "38",
    },
    {
      text: "92",
      value: "68",
    },
    {
      text: "183",
      value: "105",
    },
    {
      text: "365",
      value: "150",
    },
  ],
  [
    {
      text: "31",
      value: "61",
    },
    {
      text: "92",
      value: "110",
    },
    {
      text: "183",
      value: "172",
    },
    {
      text: "365",
      value: "245",
    },
  ],
]);
const overlayShow = ref(false);
const strDate = ref<any>();
const daysIndex = ref(-1); //选择天数的下标
const days = ref<number>(0) as any; //有效天数
const checked = ref(false); //投保须知选中
const formRef = ref<FormInstance>();

const cost = ref<number>(0); //总保费
const edit = ref(true); //是否可以修改
const param = reactive<sumbitType>({
  id: "",
  bx_id: "", //保险id
  start_time: "", //开始时间
  end_time: "", //结束时间
  insure: {
    name: "", //投保人名称
    card_type: "", //投保人证件类型
    card_no: "", //投保人证件号
    contact: "", //投保人联系人
    contact_mobile: "", //投保人联系人手机号
    mailbox: "", //邮箱
    insure_type: "", //传个人或者单位文字
    address: ""
  },
  insured: [],
  treetop: {
    type: "",
    name: "",
    structure: "",
    area_num: "",
    province: "",
    city: "",
    area: "",
    address_id: "",
    room_no: "",
    fanan: "",
    address: "",
  },
  duty: [] as any,
  annex: [],
  user: [],
  card_type: "",
  job_code: "",
  province: "",
  city: "",
  area: "",
  address: "",
  province_code: "",
  city_code: "",
  area_code: "",
  add_price: 0,
  is_show: "1",
  fananCost: 0,
  mark:[] as any
});
//获取投保页信息
const Info = ref({} as any);
const infoTbrxx = reactive<infoTbrxxType>({
  name: "",
  card_type: "",
  card_no: "",
  contact: "",
  contact_mobile: "",
  mailbox: "",
  insure_type: "",
  address: ""
});
const infoCategory = reactive<categoryInfoType>({
  job_code: "",
  category: "",
});
const categoryArr = ref([]); //职业类别回显数据
//const userArr = ref([]); //被保人清单回显数据
const dialogTime = ref(5);
const personCost = ref<number>(0)
const tbrxxRef = ref<InstanceType<typeof tbrxx>>();
const userRef = ref<InstanceType<typeof user>>();
const fananIndex = ref(0);
const categoryRef = ref<InstanceType<typeof category>>();
const fjInsuredRef = ref<InstanceType<typeof fjInsured>>();
const ysRef = ref<InstanceType<typeof ys>>();
const addressVueRef = ref<InstanceType<typeof addressVue>>();
const responsibilityRef = ref<InstanceType<typeof responsibility>>();
const uploadRef = ref<InstanceType<typeof upload>>();
const filterYear = ref();
const filterMonth = ref();
const filterDay = ref();
const currentDate = computed(() => {
  let date = new Date();
  year.value = date.getFullYear(); //获取完整的年份(4位)
  month.value = date.getMonth() + 1; //获取当前月份(0-11,0代表1月)
  month.value = month.value < 10 ? "0" + month.value : month.value;
  strDate.value = date.getDate() + 1; // 获取当前日(1-31)
  strDate.value = strDate.value < 10 ? "0" + strDate.value : strDate.value;
  let data = [`${year.value}`, `${month.value}`, `${strDate.value}`]
  return data;
});
watchEffect(() => {
  if (param.user.length > 0 && param.fananCost) {
    countCost();
  }
});
onBeforeRouteLeave(() => {
  if (!route.query.order_id) {
    setSession();
  }
  if (stopFun) {
    stopFun();
  }
  param.mark = [];
});
let stopFun: listenerHandler | undefined;
//开始录制
const player = () => {
  let stop = rrweb.record({
    emit(event: any) {
      if(param.mark)
      param.mark.push(event);
    },
  });
  stopFun = stop;
};
const Edit = () => {
  edit.value = true;
  player();
}
const openNotice = () => {
  if (!checked.value) return showToast("请阅读协议");
  noticeShow.value = true;
  countDown();
};
//倒计时
const countDown = () => {
  let t = setInterval(() => {
    if (dialogTime.value > 0) {
      dialogTime.value--;
    }

    if (dialogTime.value <= 0) {
      clearInterval(t);
    }
  }, 1000);
};

//缓存数据
const setSession = () => {
  setParam();
  sessionStorage.setItem("zj_sxs", JSON.stringify(param));
};
//跳转条款
const clickPush = (type: number) => {
  if (type == 3) {
    articleShow.value = true;
    return;
  }
  router.push(`/h5/article?types=${type}&id=${route.query.id}`);
};
//产品条款
const clickArticle = (item: any, type: number) => {
  router.push(`/h5/article?types=${type}&id=${item.id}`);
}; //计算保费
const change = () => {
  if (daysIndex.value == -1) return;
  param.fananCost = Number(
    dataSelect.value[fananIndex.value][daysIndex.value].value
  );
  countCost();
};
//计算保费
const countCost = () => {
  cost.value =
    (Number(param.fananCost) + Number(param.add_price)) * param.user.length;
  personCost.value = Number(param.fananCost);
};
//子组件方案选择的下标
const onConfirm = (index: number) => {
  fananIndex.value = index;
  if (daysIndex.value <= -1) return;
  param.fananCost = Number(
    dataSelect.value[fananIndex.value][daysIndex.value].value
  );
  countCost();
  // console.log("方案下标" + fananIndex.value + " 天数下标" + daysIndex.value);
};
const pickerChnage = (value: any) => {

  filterYear.value = value.selectedValues[0];
  filterMonth.value = value.selectedValues[1];
  filterDay.value = value.selectedValues[2];
  // console.log(filterYear.value);
};
//过滤时间
const filter = (type: any, options: any) => {
  if (type == "year") {
    return options.filter(
      (option: any) => Number(option.value) >= new Date().getFullYear()
    );
  }
  if (type == "day") {
    return filterDayDate(options);
  }
  if (type == "month") {
    return filterMonthDate(options);
  }

  return options;
};
//过滤月份
const filterMonthDate = (options: any) => {
  // console.log(filterYear.value);
  if (filterYear.value == new Date().getFullYear()) {
    return options.filter(
      (option: any) => Number(option.value) >= new Date().getMonth() + 1
    );
  } else {
    return options;
  }
};
//过滤天数
const filterDayDate = (options: any) => {
  // console.log(filterYear.value);
  if (
    filterMonth.value == new Date().getMonth() + 1 &&
    filterYear.value == new Date().getFullYear()
  ) {
    return options.filter(
      (option: any) => Number(option.value) >= new Date().getDate() + 1
    );
  } else {
    return options;
  }
};
//获取职业类别
const getCategory = async () => {
  const res = await getJobClassify("");
  categoryArr.value = res.msg;
};
//获取当前时间
const getDate = () => {
  let date = new Date();
  filterYear.value = new Date().getFullYear();
  filterMonth.value = date.getMonth() + 1;
  year.value = date.getFullYear(); //获取完整的年份(4位)
  month.value = date.getMonth() + 1; //获取当前月份(0-11,0代表1月)
  month.value = month.value < 10 ? "0" + month.value : month.value;
  strDate.value = date.getDate() + 1; // 获取当前日(1-31)
  strDate.value = strDate.value < 10 ? "0" + strDate.value : strDate.value;
  routeType.value = route.query.type as string;
  let data = [`${year.value}`, `${month.value}`, `${strDate.value}`];
  startTimer.value = year.value + "-" + month.value + "-" + strDate.value;
  getCategory();
  return data;
};
//获取缓存数据
const getSession = () => {
  if (sessionStorage.getItem("zj_sxs")) {
    let key: keyof sumbitType;
    for (key in param) {
      param[key] = JSON.parse(sessionStorage.getItem("zj_sxs") as string)[key];
    }
    let infokey: keyof infoTbrxxType;
    for (infokey in infoTbrxx) {
      infoTbrxx[infokey] = param.insure[infokey] as string
    }
    // userArr.value = param.user as any;

    startTimer.value = param.start_time;
    endTimer.value = param.end_time;
    let star = new Date(startTimer.value).getTime();
    let end = new Date(endTimer.value).getTime();
    days.value = (end - star) / (1000 * 3600 * 24) + 1;
    dataSelect.value[0].forEach((item: any, index: number) => {
      if (item.text == days.value) {
        daysIndex.value = index;
      }
    });
    countCost();

    //  cost.value = (param.fananCost as number) + (param.add_price as number);
  }
};
getDate();
//获取投保页面信息
const getInfo = async () => {
  if (route.query.id && !route.query.order_id) {
    const res = await getInsureInfo({ id: route.query.id });

    Info.value = res.msg;

    getSession();
    getDate();

    Info.value.duty[1].data.forEach((item: any, i: number) => {
      if (i == 0) {
        item['disabled'] = false
      } else {
        item['disabled'] = true
      }
    })

    if (!param.fananCost) {
      param.fananCost = res.msg.duty[0].price;
    }
    player()
    countCost();
  } else {
    sessionStorage.removeItem("zj_sxs");
    //详情页
    const res = await orderDetail({ id: route.query.order_id });
    edit.value = false;
    let key: keyof infoTbrxxType;
    for (key in infoTbrxx) {
      infoTbrxx[key] = res.msg.insure[key];
    }

    infoCategory.category = res.msg.job_code_name;
    infoCategory.job_code = res.msg.job_code;
    // userArr.value = res.msg.user;
    param.user = res.msg.user;
    Info.value = res.msg;
    Info.value.name = res.msg.bx_info.name;
    Info.value.brand = res.msg.bx_info.brand;
    Info.value.doc = res.msg.bx_info.doc
    startTimer.value = res.msg.start_time;
    endTimer.value = res.msg.end_time;
    param.add_price = res.msg.add_price;
    param.mark = res.msg.mark
    let star = new Date(startTimer.value).getTime();
    let end = new Date(endTimer.value).getTime();
    days.value = (end - star) / (1000 * 3600 * 24) + 1;
    Info.value.state = res.msg.state;
    dataSelect.value[0].forEach((item: any, index: number) => {
      if (item.text == days.value) {
        daysIndex.value = index;
      }
    });
    res.msg.duty[0].data.forEach((item: any, i: number) => {
      if (item.value == res.msg.duty[0].price) {
        fananIndex.value = i;
      }
    });
    param.fananCost = Number(dataSelect.value[fananIndex.value][daysIndex.value].value);
    cost.value = Number(res.msg.total_price);
  }
};
getInfo();
// 时间戳：1637244864707
/* 时间戳转换为时间 */
const timestampToTime = (timestamp: any) => {
  timestamp = timestamp ? timestamp : null;
  let date = new Date(timestamp); //时间戳为10位需*1000，时间戳为13位的话不需乘1000
  let Y: any, M: any, D: any;
  Y = date.getFullYear();
  M = date.getMonth() + 1;
  M = M < 10 ? "0" + M : M;
  D = date.getDate();
  D = D < 10 ? "0" + D : D;

  return Y + "-" + M + "-" + D;
};
//选择时间
const pickerConfirm = ({
  selectedValues,

  selectedIndexes,
}: {
  selectedValues: any;
  selectedOptions: any;
  selectedIndexes: any;
}) => {
  if (type.value == 0) {
    startTimer.value =
      selectedValues[0] + "-" + selectedValues[1] + "-" + selectedValues[2];
    let star = startTimer.value + " 00:00:00";

    let date1 = new Date(star).getTime();

    let time = date1 - 1000 * 3600 * 24 + days.value * 1000 * 3600 * 24;

    endTimer.value = timestampToTime(time);
  } else if (type.value == 2) {
    //有效天数
    days.value = selectedValues[0];
    let data = new Date(startTimer.value).getTime();
    // console.log(data);
    let endtime =
      data - 1000 * 3600 * 24 + Number(days.value) * 1000 * 3600 * 24;
    // console.log(endtime);
    endTimer.value = timestampToTime(endtime);
    daysIndex.value = selectedIndexes[0];

    if (fananIndex.value >= 0) {
      param.fananCost = Number(
        dataSelect.value[fananIndex.value][daysIndex.value].value
      );
    }
  }

  countCost();
  // if (type.value) {
  //   endTimer.value =
  //     selectedValues[0] + "-" + selectedValues[1] + "-" + selectedValues[2];
  // } else {
  //   startTimer.value =
  //     selectedValues[0] + "-" + selectedValues[1] + "-" + selectedValues[2];
  // }
  showBottom.value = false;
};
const openPicker = (i: number) => {
  //i 0是开始时间 1是结束数据 2是有效天数

  if (!edit.value) return;

  type.value = i;
  showBottom.value = true;
};
//重组数据
const setParam = () => {
  param.bx_id = route.query.id as string;
  let tbrxxKey: keyof insureType;
  for (tbrxxKey in param.insure) {
    param.insure[tbrxxKey] = tbrxxRef.value?.Info[tbrxxKey] as string;
  }
  param.address = addressVueRef.value?.addInfo.address as any;
  param.job_code = categoryRef.value?.Info.job_code;

  param.user = userRef.value?.user;
  let treekey: keyof treetopType;
  for (treekey in param.treetop) {
    param.treetop[treekey] = ysRef.value?.Info[treekey];
  }
  param.insured = fjInsuredRef.value?.list;
  param.start_time = startTimer.value;
  param.end_time = endTimer.value;
  param.duty = responsibilityRef.value?.list;
  param.annex = uploadRef.value?.uploadList;
};
const sumbit = () => {
  if (!checked.value) return showToast("请阅读协议");
  noticeShow.value = false;
  formRef.value
    ?.validate()
    .then(async (_) => {
      setParam();
      if (stopFun) {
        stopFun()
      }
      const res = await addOrder(param);
      if (res.code == 1) {
        sessionStorage.removeItem("zj_sxs");
        showToast("提交成功");
        let order_id = res.msg;

        router.replace(
          `/h5/insure/zj_sxs?id=${param.bx_id}&order_id=${order_id}&type=1`
        );
        routeType.value = "1";
        route.query.order_id = res.msg;
        edit.value = false;
        getInfo();
      } else {
        showToast(res.msg);
      }
    })
    .catch((_) => { });
};
//支付
const pay = async () => {
  if (edit.value) {
    //提交保单
    sumbit();
  } else {
    // 支付
    overlayShow.value = true;
    const res = await submitApi({ id: route.query.order_id });
    // showToast(res.msg);
    if (res.code == 1) {
      window.location.href = res.msg;
      // window.open(res.msg);
    } else {
      showToast(res.msg);
    }
    overlayShow.value = false;
    // console.log(res);
  }
};
const share = () => {
  router.push("/h5/insure/share?id=" + Info.value.id);
};
</script>
<style scoped lang="scss">
:deep(.van-cell-group--inset) {
  margin: 0 !important;
}

:deep(.van-field__control::-webkit-input-placeholder) {
  color: #9b9da9;
}

.ios {
  padding-bottom: constant(safe-area-inset-bottom);
}
</style>
